package com.cloudptt.wp.ui;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import com.cloudptt.api.comm.CauseCont;
import com.cloudptt.api.comm.CheckData;
import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.product.ISysOperator;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.func.sys.SysStateInfo;
import com.cloudptt.api.product.func.sys.fsm.SysConst;
import com.cloudptt.api.product.func.sys.listener.SysListener;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ScreenManager;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.more.ServerInfoActivity;
import com.cloudptt.wp.ui.more.VersionInfoActivity;
import com.cloudptt.wp.ui.views.CustomEditText;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.BootStrapSvrInfo;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


public class Login extends Activity implements SysListener,View.OnClickListener,View.OnLongClickListener{

//	public static String THIS_FILE ="Login";
	private LinearLayout logoLL = null;
	private EditText numbEdit = null; // 鐢劕褰跨紓鏍帆濡楋拷
	private CustomEditText pwdEdit = null; // 鐎靛棛鐖滅紓鏍帆濡楋拷

//	private EditText ipEdit = null; // 鐎靛棛鐖滅紓鏍帆濡楋拷
//	private EditText portEdit = null; // 鐎靛棛鐖滅紓鏍帆濡楋拷
	private Dialog progressDialog = null;
	//	private TextView checkbox = null;

	private Button loginBtn = null; // 鐎靛棛鐖滅紓鏍帆濡楋拷

	//	private SysAgent sysAgent = null;
	//	private Product product = null;
	private SysConfig config = null;
	private ISysOperator operator = null;
	private TextView    id_notify = null;
	private int state = SysStateInfo.SysState_SvrStopState;

//	private String curIp = null;
//	private int curPort = 8380;
//	private String curFileIpStr = null;
//	private boolean isServerIpChange = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
		window.setStatusBarColor(Color.parseColor("#162F4A"));
		super.onCreate(savedInstanceState);
		Log.debug(this.getClass(), " Login  onCreate :  " + Locale.getDefault().getLanguage());
		setContentView(R.layout.login);

		logoLL = (LinearLayout) findViewById(R.id.login_logo);
		logoLL.setOnLongClickListener(this);

		numbEdit = (EditText) findViewById(R.id.nameEditText);
		pwdEdit = (CustomEditText) findViewById(R.id.passwordEditText);

		loginBtn = (Button)findViewById(R.id.loginBtn);
		loginBtn.setOnClickListener(this);

		id_notify = (TextView)findViewById(R.id.id_notify);
		id_notify = (TextView)findViewById(R.id.id_notify);
		TextView configTv = (TextView)findViewById(R.id.configTv);
		configTv.setOnClickListener(this);

		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (numbEdit.getText().toString().length() > 0)
		{
			pwdEdit.requestFocus();
			inputMethodManager.showSoftInput(pwdEdit,
					InputMethodManager.SHOW_FORCED);
		}
		else
		{
			numbEdit.requestFocus();
			inputMethodManager.showSoftInput(numbEdit,
					InputMethodManager.SHOW_FORCED);
			inputMethodManager.toggleSoftInput(0,
					InputMethodManager.HIDE_NOT_ALWAYS);
		}

		if(numbEdit.getText().toString().length() > 0 && pwdEdit.getText().toString().length() > 0){
			setLoginButtonEnable(true);
		}else{
			setLoginButtonEnable(false);
		}

		numbEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

				if(checkValid()){
					setLoginButtonEnable(true);
				}else{
					setLoginButtonEnable(false);
				}
			}
		});

		pwdEdit.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(checkValid()){
					setLoginButtonEnable(true);
				}else{
					setLoginButtonEnable(false);
				}
			}
		});


		ScreenManager.getScreenManager().pushActivity(Login.this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.debug(this.getClass(), "onResume");

		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		if(product != null) {
			product.setSysListener(this.getClass().getName(),this);
			this.operator = (ISysOperator) product.getSysOperator();
			//		product.checkCurVersion(this,false,true,SysApplication.APP_KEY);

			this.config = product.getSysConfig();
			resetSvrStatueDscp();
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(R.id.loginBtn == v.getId()){
			doLoginAction();
		}
		else if(R.id.configTv == v.getId())
		{
			goToConfig();
		}
	}
	private void goToConfig()
	{
		Intent intent = new Intent();
		intent.setClass(Login.this, ServerInfoActivity.class);
		intent.putExtra(ServerInfoActivity.KEY,true);
		startActivity(intent);
	}
	@Override
	public boolean onLongClick(View v) {
		// TODO Auto-generated method stub
		return false;
	}

	public void doLoginAction()
	{
		if (this.operator == null
				|| config == null)
		{
			CommDlg.showToast(Login.this, getString(R.string.login_failed_network));
			return;
		}

		SysApplication app = ((SysApplication) getApplicationContext());
		Product product = app.getProduct();
		boolean isConnectNetwork = product.isConnectNetwork();
		Log.debug(this.getClass(), "doLoginAction isConnectNetwork = " + isConnectNetwork);
		if(!isConnectNetwork)
		{
			CommDlg.showToast(Login.this, getString(R.string.network_disconnect));
			return;
		}
		SysStateInfo info = product.getSysStateInfo();
		Log.debug(this.getClass(), "doLoginAction info = " + info);
		if(info != null
				&& info.getState()== SysStateInfo.SysState_SvrStopState)
		{
			CommDlg.showToast(Login.this, getString(R.string.long_srv_stop));
			return;
		}

		String mcId = this.numbEdit.getText().toString().trim();
		String pwd = this.pwdEdit.getText().toString().trim();
		if (!checkData(mcId,pwd))
		{
			return;
		}

		try
		{
			config.setUserInfoBeforLogin(mcId, pwd);
//			if(isServerIpChange)
//			{
//				config.setServerInfo(ipStr, 5060);
//			}
			Log.debug(this.getClass(), "doLoginAction");
			int result = this.operator.doSysAction(SysConst.SysAction_Auth);
			if(result != CauseCont.OperateCheck_Suc)
			{
				String errStr = CauseCont.getOperateCheckErrStr(result,Login.this);
				CommDlg.showToast(Login.this,errStr);
				return;
			}

			showWaitCover(true);
		}
		catch (Exception e) {
			// TODO: handle exception
		}

	}

	private boolean checkData(String num,String pwd)
	{
		if (num.equals("") || pwd.equals("")) {
			CommDlg.show(this, getResources().getString(R.string.login_failed_error_input));
			return false;
		}
		return true;
	}

	@Override
	// 閸氼垰濮╂潻婊呪柤閺堝秴濮焌idl
	protected void onDestroy() {
		super.onDestroy();
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitBy2Click(); // 鐠嬪啰鏁ら崣灞藉毊闁拷閸戝搫鍤遍弫锟�
		}
		return false;
	}
	@Override
	public void onSysState(SysStateInfo stateInfo) {
		// TODO Auto-generated method stub
		Log.debug(this.getClass(), "onSysState  stateInfo = " + stateInfo);
		int state = stateInfo.getState();
		int cause = stateInfo.getCause();
		if(SysStateInfo.SysState_SvrStartState == state )
		{
			showWaitCover(false);
			if(cause != SysStateInfo.Cause_Password
					&& cause != SysStateInfo.Cause_Publish_None
					&& cause != SysStateInfo.Cause_Failed)
			{
				int result = this.operator.doSysAction(SysConst.SysAction_Auth);
				if (result != CauseCont.OperateCheck_Suc) {
					String errStr = CauseCont.getOperateCheckErrStr(result, Login.this);
					CommDlg.showToast(Login.this, errStr);
					return;
				}
			}
			else
			{
				String errStr = CauseCont.getAuthErrStr(cause, Login.this);
				CommDlg.showToast(Login.this, errStr);
			}
		}
		else if(SysStateInfo.SysState_SipPulishSucState == state)
		{
			showWaitCover(false);
			ScreenManager.getScreenManager().popAllActivity();

		}
		else {
			showWaitCover(false);
		}
		resetSvrStatueDscp();
	}
	@Override
	public void onErrer(String str)
	{}

	private void resetSvrStatueDscp()
	{
		if(id_notify != null)
		{
			SysApplication app = ((SysApplication) getApplicationContext());
			Product product = app.getProduct();
			String srvStatusDscp = product.getSrvStatusDscp();
			id_notify.setText(srvStatusDscp);
		}
	}

	private void showWaitCover(final boolean show)
	{
		if (show)
		{
			progressDialog = UiDlg.createLoadingDialog(Login.this,
					getString(R.string.please_wait));
			progressDialog.show();
		}
		else
		{
			if(progressDialog != null)
			{
				progressDialog.dismiss();
			}
		}
	}



	private static Boolean isExit = false;

	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false)
		{
			isExit = true; // 閸戝棗顦柅锟介崙锟�

			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 閸欐牗绉烽柅锟介崙锟�
				}
			}, 2000); // 婵″倹鐏�2缁夋帡鎸撻崘鍛梾閺堝瀵滄稉瀣箲閸ョ偤鏁敍灞藉灟閸氼垰濮╃�规碍妞傞崳銊ュ絿濞戝牊甯�閸掓碍澧犻幍褑顢戦惃鍕崲閸旓拷
		}
		else
		{
			ScreenManager.getScreenManager().popAllActivity();

			SysApplication app = ((SysApplication)getApplicationContext());
			Product product = app.getProduct();
			product.doExit();

			System.exit(0);
		}
	}

	private void setLoginButtonEnable(boolean enable){
		loginBtn.setEnabled(enable);
		if(enable){
			loginBtn.setBackgroundColor(Color.parseColor("#1992FF"));
			loginBtn.setTextColor(Color.parseColor("#FFFFFF"));
		}else{
			loginBtn.setBackgroundColor(Color.parseColor("#04859F"));
			loginBtn.setTextColor(Color.parseColor("#8BC8FF"));
		}
	}

	private boolean checkValid(){
		if(numbEdit.getText().toString().length() > 0
				&& pwdEdit.getText().toString().length() > 0){
			return true;
		}else{
			return false;
		}
	}

	//	int checkedItemId = R.id.sys_default;
	//	private void showPopupMenu(final Context context, View ancher) {
	//        PopupMenu popupMenu = new PopupMenu(context, ancher);
	//        //瀵洖鍙嗛懣婊冨礋鐠у嫭绨�
	//        popupMenu.inflate(R.menu.language_selection);
	//        String lan = sharedPreferences.getString(Const.SHARED_PROP_LANGUAGE, Const.LAN_SYSTEM);
	//        //鐠佸墽鐤嗛柅澶夎厬
	//        checkedItemId = R.id.sys_default;
	//        if( lan.equals(Const.LAN_ZH_CN) )
	//        {
	//        	checkedItemId = R.id.simplified_chinese;
	//        }
	//        else if( lan.equals(Const.LAN_EN_US) )
	//        {
	//        	checkedItemId = R.id.english;
	//        }
	//        popupMenu.getMenu().findItem(checkedItemId).setChecked(true);
	//        //閼挎粌宕熸い鍦畱閻╂垵鎯�
	//        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
	//            public boolean onMenuItemClick(MenuItem menuItem) {
	//            	int pos = 0;
	//            	String lanStr = "";
	//                switch (menuItem.getItemId()) {
	//                    case R.id.sys_default:
	//                    	lanStr = Const.LAN_SYSTEM;
	//                        break;
	//                    case R.id.simplified_chinese:
	//                    	pos = 1;
	//                    	lanStr = Const.LAN_ZH_CN;
	//                        break;
	//                    case R.id.english:
	//                    	pos = 2;
	//                    	lanStr = Const.LAN_EN_US;
	//                        break;
	//                }
	//                if( checkedItemId != menuItem.getItemId() ){
	//	                SharedPreferences.Editor editor = sharedPreferences.edit();
	//	                editor.putString(Const.SHARED_PROP_LANGUAGE, lanStr);
	//	                editor.commit();
	//	                
	//	                LanguageSelection.changeAppLanguage(getResources(), pos);
	//	                
	//			        android.os.Process.killProcess(android.os.Process.myPid());  
	//                }
	//		        
	//                return true;
	//            }
	//        });
	// 
	//        //閺勫墽銇歅opupMenu
	//        popupMenu.show();
	//    }

	@Override
	public void onKeepAlive(boolean arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onForceDetach() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSvrRestart() {
		// TODO Auto-generated method stub

	}
}
